package com.zp.demopractice1.me;

import android.content.Context;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StyleRes;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.socks.library.KLog;
import com.zp.demopractice1.MZBannerView.MZBannerView;
import com.zp.demopractice1.MZBannerView.MZHolderCreator;
import com.zp.demopractice1.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by izp on 2017/6/8.
 */

public class BannerPager<T> extends FrameLayout {
    private ViewPager mViewPager ;
    private LinearLayout mIndicatorView;
    private boolean mIsAutoPlay = true;// 是否自动播放
    private List<T> mDatas;
    private BannerPagerAdapter mAdapter;
    private int mCurrentItem = 0;//当前位置
    private int []mIndicatorRes= new int[]{R.drawable.mz_banner_indicator_normal,R.drawable.mz_banner_indicator_selected};
    private ArrayList<ImageView> mIndicators = new ArrayList<>();

    public BannerPager(@NonNull Context context) {
        super(context);
        init();
    }

    public BannerPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BannerPager(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public BannerPager(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }
    private void init(){
        initViewPager();
        initIndicatorView();
    }
    private void setPages(List<T> list){
        if(list == null ){
            return;
        }
        mDatas = list;
        mAdapter = new BannerPagerAdapter(list,mViewPager,true);


    }

    private void initIndicatorView() {
        mIndicatorView = new LinearLayout(getContext());
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;//位运算
        mIndicatorView.setOrientation(LinearLayout.HORIZONTAL);
        mIndicatorView.setPadding(getResources().getDimensionPixelSize(R.dimen.dimen_12dp),0,0,getResources().getDimensionPixelSize(R.dimen.dimen_12dp));
        mIndicatorView.setLayoutParams(layoutParams);
        for(int i=0;i<mDatas.size();i++){
            ImageView imageView = new ImageView(getContext());
            imageView.setPadding(6,0,6,0);
            if(i == (mCurrentItem % mDatas.size())){
                imageView.setImageResource(mIndicatorRes[1]);
            }else{
                imageView.setImageResource(mIndicatorRes[0]);
            }
            mIndicators.add(imageView);
            mIndicatorView.addView(imageView);
        }
    }

    private void initViewPager() {
        mViewPager = new ViewPager(getContext());
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mViewPager.setLayoutParams(layoutParams);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                KLog.i("position :"+position+"    positionOffset :"+positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                KLog.i("onPageSelected :"+position);
                mCurrentItem = position;
                updateLinearPosition();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        addView(mViewPager);
    }

    private void updateLinearPosition() {
        // 切换indicator
        int realSelectPosition = mCurrentItem % mIndicators.size();
        if (null!=mDatas && mDatas.size()>=0){
            for(int i=0;i<mDatas.size();i++){
                if(i == realSelectPosition){
                    mIndicators.get(i).setImageResource(mIndicatorRes[1]);
                }else{
                    mIndicators.get(i).setImageResource(mIndicatorRes[0]);
                }
            }
        }
    }

    public static class BannerPagerAdapter<T> extends PagerAdapter{
        private List<T> mDatas;
        private boolean canLoop;
        private ViewPager mViewPager;
        public BannerPagerAdapter(List<T> datas, ViewPager viewPager,boolean canLoop) {
            this.mDatas = datas;
            this.canLoop = canLoop;
            mViewPager = viewPager;
            mViewPager.setAdapter(this);
            mViewPager.getAdapter().notifyDataSetChanged();
            int currentItem = canLoop ? getStartSelectItem():0;
            //设置当前选中的Item
            mViewPager.setCurrentItem(currentItem);
        }
        @Override
        public int getCount() {
            return canLoop ?Integer.MAX_VALUE : getRealCount();//ViewPager返回int 最大值
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view ==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = getView(position,container);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public void finishUpdate(ViewGroup container) {
            // 轮播模式才执行
            if(canLoop){
                int position = mViewPager.getCurrentItem();
                if (position == getCount() - 1) {
                    position = 0;
                    setCurrentItem(position);
                }
            }
        }

        private int getRealCount(){
            return  mDatas==null ? 0:mDatas.size();
        }
        private void setCurrentItem(int position){
            try {
                mViewPager.setCurrentItem(position, false);
            }catch (IllegalStateException e){
                e.printStackTrace();
            }
        }
        private int getStartSelectItem(){
            // 我们设置当前选中的位置为Integer.MAX_VALUE / 2,这样开始就能往左滑动
            // 但是要保证这个值与getRealPosition 的 余数为0，因为要从第一页开始显示
            int currentItem = Integer.MAX_VALUE / 2;
            if(currentItem % getRealCount()  ==0 ){
                return currentItem;
            }
            // 直到找到从0开始的位置
            while (currentItem % getRealCount() == 0){
                currentItem++;
            }
            return currentItem;
        }

        private View getView(int position,ViewGroup container){
            final int realPosition = position % getRealCount();//如果position比count小，那么取模运算就返回本身。如果大于时，position是真实数量的倍数来确定
            ImageView imageView = new ImageView(container.getContext());
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            imageView.setLayoutParams(layoutParams);
            if (mDatas.get(realPosition) instanceof Integer){
//                imageView.setImageResource((int) mDatas.get(realPosition));
            }else if (mDatas.get(realPosition) instanceof String){

            }else if (mDatas.get(realPosition) instanceof File){

            }
            return imageView;
        }

    }
}
